//xlang Source, Name:Server.xcsm 
//Date: Sat Oct 11:28:29 2018 

class Server : IServer{
    public Server(BusinessSrv vb){
        bs = vb;
    }
	//通用网络服务器接口
	Unsi unsi = new Unsi();
    BusinessSrv bs;
    static const String TAG = "XRCP";
    //远程调用服务
	RCPServer rcp = new RCPServer();
    
    long _svnsrv_content = 0;
    //消息回调通知
    IRCPEventHandler rcph = new IRCPEventHandler(){
		bool onNewInstance(long context, int type)override{
			return true;
        }
        
		bool onDeleteInstance(long context)override{
            if (_svnsrv_content != 0 && unsi.equalsHandle(context,_svnsrv_content)){
                releaseClient();
            }
			return true;
        }
        
        void onAccessFailed(long context)override{
        
        }
        
        bool onTimeout(long context)override{
			return false;
        }
    };
    
    void releaseClient(){
        if (_svnsrv_content != 0){
            unsi.getAsyncDirectOutput().releaseContext(_svnsrv_content);
        }
        _svnsrv_content = 0;
    }
    
    bool login(long context, String key){
        if (key == BusinessSrv.getKey()){
            releaseClient();
            _svnsrv_content = unsi.clone(context);
            return true;
        }
        return false;
    }
    
    void onrecv(long context, int id, byte [] data,int offset, int len){
        bs.onrecv(id, data, offset, len);
    }
        
    void onSVNClose(long context, int id){
        bs.onSVNClose(id);
    }
    
    public bool isValid(){
        return _svnsrv_content != 0;
    }
    
    public void newConnect(int id){
        if (_svnsrv_content == 0){
            return;
        }
        rcp.rcs.newConnect(_svnsrv_content,id);
    }
    
    public void onheart(long ctx,int v){
        rcp.rcs.onheartRelay(ctx, v + 1);
        if (_svnsrv_content == 0){
            _svnsrv_content = unsi.clone(ctx);
        }
    }
    
    public void write(int id, byte[] data, int offset, int length){
        if (_svnsrv_content == 0){
            return;
        }
        rcp.rcs.write(_svnsrv_content,id,data,offset,length );
    }
    
    public void onClose(int id){
        if (_svnsrv_content == 0){
            return;
        }
        rcp.rcs.onClose(_svnsrv_content,id);
    }
    
    public bool create(int port){
		return rcp.create(this, rcph, unsi, port);
    }
};